﻿using GalaSoft.MvvmLight;
using WP7Contrib.Collections;
using CDFWPUG.Model;
using System;
using System.Linq;
using System.Net;
using Microsoft.Phone.Net.NetworkInformation;
using GalaSoft.MvvmLight.Command;
using System.Windows.Controls;

namespace CDFWPUG.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class pageLinksViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the pageLinksViewModel class.
        /// </summary>
        public pageLinksViewModel()
        {
            Links = new ObservableCollection<Link>();
            SelectedLinkItem = new Model.Link();
            LinkSelectedCommand = new RelayCommand<SelectionChangedEventArgs>(HandleLinkSelectedCommand);
            LinkRefreshCommand = new RelayCommand(HandleLinkRefreshCommand);

            if (IsInDesignMode)
            {
                Links = Helpers.LinksHelper.Test_GetLinks();
            }
            else
            {
                LoadLinks();
            }

        }

         
        #region Properties
            private ObservableCollection<Link> _Links;
            public ObservableCollection<Link> Links
            {
                get
                {
                    return _Links;
                }
                set
                {
                    if (_Links != value)
                    {
                        _Links = value;
                        RaisePropertyChanged("Links");
                    }
                }
            }


            private Boolean _LinksLoading;
            public Boolean LinksLoading
            {
                get { return _LinksLoading; }
                set
                {
                    if (_LinksLoading != value)
                    {
                        _LinksLoading = value;
                        RaisePropertyChanged("LinksLoading");
                    }

                }
            }

            private String _LinksMessage;
            public String LinksMessage
            {
                get { return _LinksMessage; }
                set
                {
                    if (_LinksMessage != value)
                    {
                        _LinksMessage = value;
                        RaisePropertyChanged("LinksMessage");
                    }

                }
            }

            private Model.Link _SelectedLinkItem;
            public Model.Link SelectedLinkItem
            {
                get
                {
                    return _SelectedLinkItem;
                }
                set
                {
                    _SelectedLinkItem = value;
                    RaisePropertyChanged("SelectedLinkItem");
                }
            }


        #endregion

            #region Commands

            public RelayCommand<SelectionChangedEventArgs> LinkSelectedCommand { get; private set; }
            private void HandleLinkSelectedCommand(SelectionChangedEventArgs e)
            {
                if (e.AddedItems.Count > 0)
                {
                    string address = SelectedLinkItem.Url;
                    Helpers.FunctionsHelper.CreateWebsiteTask(address);
                }
            }


            public RelayCommand LinkRefreshCommand { get; private set; }
            private void HandleLinkRefreshCommand()
            {
                UpdateLinks();
            }


            #endregion


            public void LoadLinks()
            {
                if (Helpers.IsolatedStorageHelper.FileExists("Links.xml"))
                {
                    LinksLoading = true;
                    var results = Helpers.LinksHelper.GetLinksFromIsolatedStorage();
                    Links.Clear();
                    foreach (var item in results)
                    {
                        Links.Add(item);
                    }
                    LinksLoading = false;
                }
                else
                {
                    //no file in isolated storage so download it
                    UpdateLinks();
                }
            }

            public void UpdateLinks()
            {
                WebClient appsFeed = new WebClient();
                bool hasNetworkConnection = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
                string xmldata = "http://bugail.com/cdfwpug/data/Links.xml?guid=" + Guid.NewGuid();

                if (hasNetworkConnection == true)
                {
                    LinksLoading = true;
                    appsFeed.DownloadStringCompleted += new DownloadStringCompletedEventHandler(appsFeed_DownloadStringCompleted);
                    appsFeed.DownloadStringAsync(new Uri(xmldata));
                }
                else
                {
                    LinksMessage = "There is currently no network coverage, try again later";
                    Links.Clear();
                    LinksLoading = false;
                }
            }

            void appsFeed_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    string xml = e.Result;
                    if (Helpers.IsolatedStorageHelper.FileExists("Links.xml"))
                    {
                        Helpers.IsolatedStorageHelper.DeleteFile("Links.xml");
                    }
                    Helpers.IsolatedStorageHelper.SaveFile("Links.xml", xml);
                    LoadLinks();
                }
                else
                {
                    LinksMessage = "Opps! There was a problem while getting the links, please try again later";

                }
                LinksLoading = false;
            }

        ////public override void Cleanup()
        ////{
        ////    // Clean own resources if needed

        ////    base.Cleanup();
        ////}
    }
}